
package com.starbaba.channelmanager.view;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.channel.model.Comm_product_channel;
import com.starbaba.channelmanager.model.Channel;
import com.starbaba.channelmanager.model.Product;
import com.starbaba.channelmanager.service.ChannelService;
import com.starbaba.core.service.CommonService;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.dictionary.Constant;

@SuppressWarnings({"deprecation","rawtypes","unchecked"})
public class ChannelAction extends BaseAction implements ModelDriven<Channel> {

	
    private static final long serialVersionUID = 1L;
    private Channel model;
	private ChannelService service;
	
	private InputStream input;

	private String fileName;
	
	public String getFileName() {
		return fileName;
	}

	public InputStream getInput() {
		return input;
	}
	

	@Autowired
	@Qualifier("tChannelServiceImpl")
	public void setService(ChannelService service) {
		this.service = service;
	}

	@Override
	public Channel getModel() {
		if (model==null) {
			model=new Channel();
		}
		return model;
	}
	
	public String showPage() throws AppException {
		//在基础上添加产品列表
        BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);
		String sql = " SELECT DISTINCT prdid AS code,name AS kindname FROM comm_product_prdid";
		List<Product> productList = baseDao.list(sql, Product.class);
		paramsMap.put("productList",productList);
		return "success";
	}
	
	public String getInfo() throws AppException {
		
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);  //将请求参数封装带paramsMap中
		//在基础上添加产品列表
		BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);
		String sql = " SELECT DISTINCT prdid AS code,name AS kindname FROM comm_product_prdid";
		List<Product> productList = baseDao.list(sql, Product.class);
		paramsMap.put("productList",productList);
		
		String op = (String)paramsMap.get("op");
		paramsMap.put("op", op);
		if ("1".equals(op)) {
			String channel_name = (String)paramsMap.get("channel_name");
			String channel_code = (String)paramsMap.get("channel_code");
			String prdid = (String)paramsMap.get("prdid");
			paramsMap.put("channel_name", channel_name);
			paramsMap.put("channel_code", channel_code);
			paramsMap.put("prdid", prdid);
		}
		return "success";
	}
	
	public String uploadChannelList() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		String value = service.getExportString(service.queryChannelVo(paramsMap, null, null, pageResponse));
		input = new ByteArrayInputStream(value.getBytes("GBK"));
		fileName = System.currentTimeMillis() + ".csv";
		return ActionSupport.SUCCESS;
	}

	
	/**
	 * 查询所有的渠道
	 */
    public void channelList() {
		parsePageRequest();
        PageResponse pageResponse=new PageResponse();
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		List list=service.queryChannelVo(paramsMap, pageRequest.getIDisplayStart(),pageRequest.getIDisplayLength(), pageResponse);
		int count=service.getProductCount(paramsMap);
		pageResponse.setITotalDisplayRecords(count);
		pageResponse.setITotalRecords(count);
		try {
			pageResponse.setAaData(list);
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询某个产品所有的渠道
	 * @throws AppException 
	 */
	public void channelListByProduct() throws AppException {
		parsePageRequest();
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String prdid = (String) paramsMap.get("id");
		BaseDao dao = new BaseDao(Constant.POOL_LIFE);
		List<Comm_product_channel> channelList = dao.list("select * from comm_product_channel where prdid = ? ", Comm_product_channel.class, prdid);
		
		JSONObject jsonObject = new JSONObject();
		JSONArray array = new JSONArray();
		for (Comm_product_channel channel : channelList) {
			JSONObject obj = new JSONObject();
			obj.put("id", channel.getChannel_code());
			obj.put("name", channel.getChannel_name());
			array.add(obj);
		}
		jsonObject.put("channels", array);
		try {
			this.sendJsonMessage(jsonObject.toJSONString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 新增渠道
	 */
	public void addNewChannel() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(
				Struts2Utils.getRequest(), paramsMap);
		try {
			boolean result = service.addChannel(paramsMap, model);
			sendJsonMessage(result ? "1" : "0");
		} catch(Exception e) {
			e.printStackTrace();
			LogService.error("getGeneraldata", e);
		}
		
	}
	/**
	 * 删除渠道
	 */
	public void dropChannel() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		try {
			String id=(String) paramsMap.get("id");
			boolean result = service.dropChannel(id);
			sendJsonMessage(result ? "1" : "0");
		} catch(Exception e) {
			e.printStackTrace();
			LogService.error("getGeneraldata", e);
		}
	}
	
	/**
	 * 更新渠道
	 */
	@SuppressWarnings("unused")
    public void updateChannel() {
        PageResponse pageResponse = new PageResponse();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		try {
			boolean result = service.updateChannel(paramsMap, model,id);
			sendJsonMessage(result ? "1" : "0");
			
		} catch(Exception e) {
			e.printStackTrace();
			LogService.error("getGeneraldata", e);
		}
	}
	/**
	 * 根据用户获取该用户关联的渠道
	 * @throws AppException 
	 */
	public void getChannelByUser() {
		String userid = userVO.getUserid();
		CommonService comservice = this.getService();
		Map<String,Object> params = new HashMap();
		params.put("userid", userid);
		List channelList = comservice.findByHQL("select c.id,c.name From Channel c,UserChannel uc where c.id=uc.channelid and uc.userid=:userid", params);
		PageResponse pageResponse = new PageResponse();
		pageResponse.setAaData(channelList);
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch(IOException e) {
			e.printStackTrace();
		}	
	}
}
